<template>
  <view class="admin-container">
    <view class="admin-header">
      <text class="title">管理员后台</text>
      <button class="logout-btn" @click="handleLogout">退出登录</button>
    </view>

    <view class="stats-container" v-if="!loading && !error">
      <view class="stat-card">
        <text class="stat-title">用户总数</text>
        <text class="stat-value">{{ stats.user_count }}</text>
      </view>
      <view class="stat-card">
        <text class="stat-title">动态总数</text>
        <text class="stat-value">{{ stats.post_count }}</text>
      </view>
      <view class="stat-card">
        <text class="stat-title">房间总数</text>
        <text class="stat-value">{{ stats.room_count }}</text>
      </view>
    </view>

    <view class="loading" v-if="loading">
      <text>加载中...</text>
    </view>

    <view class="error" v-if="error">
      <text class="error-text">{{ error }}</text>
      <button class="retry-btn" @click="fetchStats">重试</button>
    </view>
  </view>
</template>

<script>
import { getSystemStats } from '@/api/admin'
import { useUserStore } from '@/stores/user'

export default {
  data() {
    return {
      stats: {},
      loading: true,
      error: ''
    }
  },
  mounted() {
    this.fetchStats()
  },
  methods: {
    async fetchStats() {
      this.loading = true
      this.error = ''
      try {
        const response = await getSystemStats()
        this.stats = response
      } catch (err) {
        // 仅在401错误时重定向到登录页
        if (err.message.includes('401')) {
          uni.redirectTo({ url: '/pages/login/login' })
        } else {
          this.error = '统计数据加载失败: ' + (err.message || '未知错误')
        }
      } finally {
        this.loading = false
      }
    },
    handleLogout() {
      const userStore = useUserStore()
      userStore.logout()
      uni.redirectTo({ url: '/pages/login/login' })
    }
  }
}
</script>

<style scoped>
.admin-container { padding: 20px; }
.admin-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
.title { font-size: 24px; font-weight: bold; }
.logout-btn { background: #ff4d4f; color: white; padding: 8px 16px; border-radius: 4px; }
.stats-container { display: flex; gap: 20px; }
.stat-card { flex: 1; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.stat-title { color: #666; font-size: 14px; }
.stat-value { font-size: 28px; font-weight: bold; margin-top: 10px; display: block; }
.loading { text-align: center; padding: 40px; }
.error { text-align: center; padding: 40px; }
.error-text { color: #ff4d4f; margin-bottom: 20px; display: block; }
.retry-btn { background: #1890ff; color: white; padding: 8px 16px; border-radius: 4px; }
</style>